// localStorage 数据管理模块

// 存储键名
const STORAGE_KEYS = {
    POLICIES: 'data_security_policies',
    POLICY_GROUPS: 'data_security_policy_groups',
    USER_VIEWS: 'data_security_user_views',
    SETTINGS: 'data_security_settings'
};

// 获取所有策略
function getPoliciesFromLocalStorage() {
    try {
        const data = localStorage.getItem(STORAGE_KEYS.POLICIES);
        return data ? JSON.parse(data) : [];
    } catch (error) {
        console.error('读取策略数据失败:', error);
        return [];
    }
}

// 保存策略列表
function savePoliciesToLocalStorage(policies) {
    try {
        localStorage.setItem(STORAGE_KEYS.POLICIES, JSON.stringify(policies));
        return true;
    } catch (error) {
        console.error('保存策略数据失败:', error);
        return false;
    }
}

// 获取单个策略
function getPolicyById(id) {
    const policies = getPoliciesFromLocalStorage();
    return policies.find(policy => policy.id === id);
}

// 添加新策略
function addPolicy(policy) {
    const policies = getPoliciesFromLocalStorage();
    
    // 确保有ID
    if (!policy.id) {
        policy.id = generatePolicyId();
    }
    
    // 设置创建时间
    if (!policy.createdAt) {
        policy.createdAt = new Date().toISOString();
    }
    
    // 更新最后修改时间
    policy.lastModified = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
    
    policies.push(policy);
    return savePoliciesToLocalStorage(policies);
}

// 更新策略
function updatePolicy(updatedPolicy) {
    let policies = getPoliciesFromLocalStorage();
    const index = policies.findIndex(p => p.id === updatedPolicy.id);
    
    if (index === -1) {
        return false;
    }
    
    // 更新最后修改时间
    updatedPolicy.lastModified = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
    
    policies[index] = updatedPolicy;
    return savePoliciesToLocalStorage(policies);
}

// 删除策略
function removePolicy(id) {
    let policies = getPoliciesFromLocalStorage();
    policies = policies.filter(p => p.id !== id);
    return savePoliciesToLocalStorage(policies);
}

// 批量删除策略
function removePolicies(ids) {
    let policies = getPoliciesFromLocalStorage();
    policies = policies.filter(p => !ids.includes(p.id));
    return savePoliciesToLocalStorage(policies);
}

// 获取策略组
function getPolicyGroupsFromLocalStorage() {
    try {
        const data = localStorage.getItem(STORAGE_KEYS.POLICY_GROUPS);
        return data ? JSON.parse(data) : getDefaultPolicyGroups();
    } catch (error) {
        console.error('读取策略组数据失败:', error);
        return getDefaultPolicyGroups();
    }
}

// 保存策略组
function savePolicyGroupsToLocalStorage(groups) {
    try {
        localStorage.setItem(STORAGE_KEYS.POLICY_GROUPS, JSON.stringify(groups));
        return true;
    } catch (error) {
        console.error('保存策略组数据失败:', error);
        return false;
    }
}

// 获取默认策略组
function getDefaultPolicyGroups() {
    return [
        { id: 1, name: '所有策略', parentId: null, isDefault: true },
        { id: 2, name: '数据泄露防护', parentId: null, isDefault: true },
        { id: 3, name: '异常访问检测', parentId: null, isDefault: true },
        { id: 4, name: '合规性监控', parentId: null, isDefault: true }
    ];
}

// 获取用户视图配置
function getUserViewsFromLocalStorage() {
    try {
        const data = localStorage.getItem(STORAGE_KEYS.USER_VIEWS);
        return data ? JSON.parse(data) : getDefaultUserViews();
    } catch (error) {
        console.error('读取用户视图失败:', error);
        return getDefaultUserViews();
    }
}

// 保存用户视图配置
function saveUserViewsToLocalStorage(views) {
    try {
        localStorage.setItem(STORAGE_KEYS.USER_VIEWS, JSON.stringify(views));
        return true;
    } catch (error) {
        console.error('保存用户视图失败:', error);
        return false;
    }
}

// 获取默认用户视图
function getDefaultUserViews() {
    return [
        {
            id: 1,
            name: '全部策略',
            isDefault: true,
            filters: [],
            sortBy: 'lastModified',
            sortOrder: 'desc'
        },
        {
            id: 2,
            name: '已启用策略',
            isDefault: true,
            filters: [{ field: 'status', operator: '=', value: 'enabled' }],
            sortBy: 'priority',
            sortOrder: 'desc'
        },
        {
            id: 3,
            name: '高优先级策略',
            isDefault: true,
            filters: [{ field: 'priority', operator: '>=', value: 8 }],
            sortBy: 'priority',
            sortOrder: 'desc'
        }
    ];
}

// 获取用户设置
function getUserSettingsFromLocalStorage() {
    try {
        const data = localStorage.getItem(STORAGE_KEYS.SETTINGS);
        return data ? JSON.parse(data) : getDefaultUserSettings();
    } catch (error) {
        console.error('读取用户设置失败:', error);
        return getDefaultUserSettings();
    }
}

// 保存用户设置
function saveUserSettingsToLocalStorage(settings) {
    try {
        localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(settings));
        return true;
    } catch (error) {
        console.error('保存用户设置失败:', error);
        return false;
    }
}

// 获取默认用户设置
function getDefaultUserSettings() {
    return {
        sidebarCollapsed: false,
        detailPanelCollapsed: false,
        itemsPerPage: 10,
        theme: 'default',
        notifications: {
            enabled: true,
            sound: true,
            popup: true
        }
    };
}

// 生成策略ID
function generatePolicyId() {
    const policies = getPoliciesFromLocalStorage();
    let maxId = 0;
    
    policies.forEach(policy => {
        if (policy.id > maxId) {
            maxId = policy.id;
        }
    });
    
    return maxId + 1;
}

// 导入策略数据
function importPoliciesFromJSON(jsonString) {
    try {
        const importedPolicies = JSON.parse(jsonString);
        
        if (!Array.isArray(importedPolicies)) {
            throw new Error('导入数据格式错误');
        }
        
        // 验证并处理导入的策略
        const processedPolicies = importedPolicies.map(policy => {
            const newPolicy = { ...policy };
            // 生成新ID避免冲突
            newPolicy.id = generatePolicyId();
            // 更新时间戳
            newPolicy.lastImported = new Date().toISOString();
            // 重置状态为禁用
            newPolicy.status = 'disabled';
            return newPolicy;
        });
        
        // 获取现有策略
        const existingPolicies = getPoliciesFromLocalStorage();
        
        // 合并并保存
        const updatedPolicies = [...existingPolicies, ...processedPolicies];
        return savePoliciesToLocalStorage(updatedPolicies);
    } catch (error) {
        console.error('导入策略失败:', error);
        return false;
    }
}

// 导出策略数据
function exportPoliciesToJSON(policyIds = null) {
    try {
        let policies = getPoliciesFromLocalStorage();
        
        // 如果指定了ID，则只导出这些策略
        if (policyIds && Array.isArray(policyIds) && policyIds.length > 0) {
            policies = policies.filter(p => policyIds.includes(p.id));
        }
        
        // 移除不需要导出的字段
        const exportData = policies.map(policy => {
            const { createdAt, lastImported, ...exportablePolicy } = policy;
            return exportablePolicy;
        });
        
        return JSON.stringify(exportData, null, 2);
    } catch (error) {
        console.error('导出策略失败:', error);
        return null;
    }
}

// 清空所有数据
function clearAllData() {
    try {
        Object.values(STORAGE_KEYS).forEach(key => {
            localStorage.removeItem(key);
        });
        return true;
    } catch (error) {
        console.error('清空数据失败:', error);
        return false;
    }
}

// 获取统计信息
function getStatistics() {
    const policies = getPoliciesFromLocalStorage();
    
    return {
        totalCount: policies.length,
        enabledCount: policies.filter(p => p.status === 'enabled').length,
        disabledCount: policies.filter(p => p.status === 'disabled').length,
        byType: policies.reduce((acc, policy) => {
            acc[policy.type] = (acc[policy.type] || 0) + 1;
            return acc;
        }, {}),
        byGroup: policies.reduce((acc, policy) => {
            acc[policy.group] = (acc[policy.group] || 0) + 1;
            return acc;
        }, {})
    };
}

// 根据ID数组获取策略列表
function getPoliciesByIds(ids) {
    const policies = getPoliciesFromLocalStorage();
    return policies.filter(p => ids.includes(p.id));
}

// 批量更新策略状态
function batchUpdatePolicyStatus(ids, status) {
    let policies = getPoliciesFromLocalStorage();
    const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    }).replace(/\//g, '-');
    
    policies = policies.map(policy => {
        if (ids.includes(policy.id)) {
            return {
                ...policy,
                status,
                lastModified: now
            };
        }
        return policy;
    });
    
    return savePoliciesToLocalStorage(policies);
}

// 根据过滤条件搜索策略
function searchPolicies(filters) {
    let policies = getPoliciesFromLocalStorage();
    
    if (!Array.isArray(filters) || filters.length === 0) {
        return policies;
    }
    
    return policies.filter(policy => {
        return filters.every(filter => {
            const { field, operator, value } = filter;
            
            switch (operator) {
                case '=':
                    return policy[field] === value;
                case '!=':
                    return policy[field] !== value;
                case '>':
                    return policy[field] > value;
                case '<':
                    return policy[field] < value;
                case '>=':
                    return policy[field] >= value;
                case '<=':
                    return policy[field] <= value;
                case 'contains':
                    return String(policy[field]).toLowerCase().includes(String(value).toLowerCase());
                case 'startsWith':
                    return String(policy[field]).toLowerCase().startsWith(String(value).toLowerCase());
                case 'endsWith':
                    return String(policy[field]).toLowerCase().endsWith(String(value).toLowerCase());
                default:
                    return true;
            }
        });
    });
}

// 生成导出模板
function generateExportTemplate() {
    const template = [
        {
            name: '示例策略',
            type: '基础策略',
            priority: 5,
            status: 'disabled',
            group: '默认组',
            description: '这是一个策略模板示例',
            rules: [
                {
                    type: 'regex',
                    pattern: 'example-pattern',
                    description: '示例规则'
                }
            ],
            protocols: ['http', 'https'],
            actions: {
                notification: ['email', 'system'],
                control: 'alert',
                notificationType: ['real-time']
            }
        }
    ];
    
    return JSON.stringify(template, null, 2);
}

// 验证策略数据
function validatePolicy(policy) {
    const errors = [];
    
    // 验证必填字段
    if (!policy.name || policy.name.trim() === '') {
        errors.push('策略名称不能为空');
    }
    
    if (!policy.type) {
        errors.push('策略类型不能为空');
    }
    
    if (policy.priority === undefined || policy.priority === null || 
        policy.priority < 1 || policy.priority > 10 || !Number.isInteger(policy.priority)) {
        errors.push('优先级必须是1-10之间的整数');
    }
    
    if (!policy.description || policy.description.trim() === '') {
        errors.push('策略描述不能为空');
    }
    
    if (!Array.isArray(policy.rules) || policy.rules.length === 0) {
        errors.push('至少需要添加一条检测规则');
    }
    
    if (!Array.isArray(policy.protocols) || policy.protocols.length === 0) {
        errors.push('至少需要选择一个检测协议');
    }
    
    return {
        isValid: errors.length === 0,
        errors
    };
}

// 初始化数据存储
function initializeStorage() {
    // 检查是否已有数据
    if (!localStorage.getItem(STORAGE_KEYS.POLICIES)) {
        // 初始化默认数据
        const defaultPolicies = [
            {
                id: 1,
                name: '敏感数据泄露检测',
                type: '基础策略',
                priority: 9,
                status: 'enabled',
                group: '数据泄露防护',
                description: '检测敏感数据（如身份证号、银行卡号、手机号等）的泄露行为',
                lastModified: '2025-11-15 09:30:45',
                rules: [
                    { type: 'regex', pattern: '\\d{17}[\\dX]', description: '身份证号检测' },
                    { type: 'regex', pattern: '\\d{16,19}', description: '银行卡号检测' },
                    { type: 'regex', pattern: '1[3-9]\\d{9}', description: '手机号检测' }
                ],
                protocols: ['http', 'https', 'smtp', 'ftp'],
                actions: {
                    notification: ['email', 'system'],
                    control: 'alert',
                    notificationType: ['real-time', 'daily-summary']
                }
            },
            {
                id: 2,
                name: '异常访问行为监控',
                type: '高级策略',
                priority: 8,
                status: 'enabled',
                group: '异常访问检测',
                description: '监控非常规时间或非常规位置的访问行为',
                lastModified: '2025-11-14 15:20:18',
                rules: [
                    { type: 'time', condition: 'out-of-hours', description: '非工作时间访问' },
                    { type: 'location', condition: 'unusual', description: '异常位置访问' },
                    { type: 'frequency', threshold: '50/min', description: '高频访问检测' }
                ],
                protocols: ['http', 'https'],
                actions: {
                    notification: ['email', 'system', 'sms'],
                    control: 'block',
                    notificationType: ['real-time']
                }
            },
            {
                id: 3,
                name: '合规性审计规则',
                type: '自定义策略',
                priority: 7,
                status: 'disabled',
                group: '合规性监控',
                description: '根据GDPR、CCPA等法规要求的合规性审计',
                lastModified: '2025-11-13 11:05:32',
                rules: [
                    { type: 'data-classification', level: 'sensitive', description: '敏感数据处理审计' },
                    { type: 'retention', period: 'exceeded', description: '数据保留期限审计' },
                    { type: 'access-control', role: 'unauthorized', description: '未授权访问审计' }
                ],
                protocols: ['http', 'https', 'ftp', 'smb2', 'smtp'],
                actions: {
                    notification: ['email', 'system'],
                    control: 'record',
                    notificationType: ['daily-summary']
                }
            },
            {
                id: 4,
                name: '大文件传输监控',
                type: '基础策略',
                priority: 6,
                status: 'enabled',
                group: '数据泄露防护',
                description: '监控超过指定大小的文件传输行为',
                lastModified: '2025-11-12 14:35:40',
                rules: [
                    { type: 'file-size', threshold: '10MB', description: '大文件传输检测' },
                    { type: 'file-type', types: ['zip', 'rar', 'exe'], description: '敏感文件类型检测' }
                ],
                protocols: ['http', 'https', 'ftp', 'smtp'],
                actions: {
                    notification: ['email', 'system'],
                    control: 'alert',
                    notificationType: ['real-time']
                }
            },
            {
                id: 5,
                name: 'API访问频率限制',
                type: '高级策略',
                priority: 8,
                status: 'enabled',
                group: '异常访问检测',
                description: '限制API接口的访问频率，防止滥用',
                lastModified: '2025-11-11 09:12:55',
                rules: [
                    { type: 'rate-limit', requests: 100, period: 'minute', description: '每分钟请求限制' },
                    { type: 'rate-limit', requests: 1000, period: 'hour', description: '每小时请求限制' }
                ],
                protocols: ['http', 'https'],
                actions: {
                    notification: ['system'],
                    control: 'block',
                    notificationType: ['realtime']
                }
            }
        ];
        
        savePoliciesToLocalStorage(defaultPolicies);
    }
    
    // 初始化其他存储项
    if (!localStorage.getItem(STORAGE_KEYS.POLICY_GROUPS)) {
        savePolicyGroupsToLocalStorage(getDefaultPolicyGroups());
    }
    
    if (!localStorage.getItem(STORAGE_KEYS.USER_VIEWS)) {
        saveUserViewsToLocalStorage(getDefaultUserViews());
    }
    
    if (!localStorage.getItem(STORAGE_KEYS.SETTINGS)) {
        saveUserSettingsToLocalStorage(getDefaultUserSettings());
    }
}

// 当模块加载时自动初始化存储
initializeStorage();

// 暴露公共函数
window.DataManager = {
    getPolicies: getPoliciesFromLocalStorage,
    savePolicies: savePoliciesToLocalStorage,
    getPolicyById,
    addPolicy,
    updatePolicy,
    deletePolicy: removePolicy,
    deletePolicies: removePolicies,
    getPolicyGroups: getPolicyGroupsFromLocalStorage,
    savePolicyGroups: savePolicyGroupsToLocalStorage,
    getUserViews: getUserViewsFromLocalStorage,
    saveUserViews: saveUserViewsToLocalStorage,
    getUserSettings: getUserSettingsFromLocalStorage,
    saveUserSettings: saveUserSettingsToLocalStorage,
    importPolicies: importPoliciesFromJSON,
    exportPolicies: exportPoliciesToJSON,
    clearAllData,
    getStatistics,
    getPoliciesByIds,
    batchUpdatePolicyStatus,
    searchPolicies,
    generateTemplate: generateExportTemplate,
    validatePolicy,
    initializeStorage
};